const { chromium } = require("playwright"); // 或使用 'firefox' 或 'webkit'
(async () => {
  // 启动浏览器
  const browser = await chromium.launch({
    headless: false,
    timeout: 300000,
    slowMo: 500,
  });
  const context = await browser.newContext({
    viewport: {
      width: 1920, // 屏幕宽度
      height: 1080, // 屏幕高度
    },
  });
  const page = await context.newPage();
  //   const username = process.env.username;
  //   const password = process.env.password;
  //   const address = process.env.address;
  //   const home = process.env.home;
  //   const firstname = process.env.firstname;
  //   const lastname = process.env.lastname;
  const info = require("./info");
  // 访问商品页面
  await page.goto("https://www.isseymiyake.com/products/bb43ag205?");
  // 添加商品到购物车
  try {
    await page.click("button._submit.f-globalUsersModalClose");
    // await page.click(
    //   `//input[@type='radio' and @value='MATTE BLACK （no.16）']`
    // ),
    // 点击特定的 label 元素
    await page.click(`label[for="MATTE BLACK （no.16）"]`);
    await page.click(`//button[contains(@class, '_in_stock on')]`);
    await page.click(`#cart-notification-button`);
  } catch {
    (x) => console.log(x);
  }

  //   await page.click("button.add-to-cart");
  await page.fill("#Quantity-1", "1");
  // 定位并点击 button 元素
  await page.click('button.quantity__button[name="plus"]');
  await page.click("#checkout");

  await page.fill('input[name="login_email"]', info.username);
  await page.fill('input[name="login_password"]', info.password);
  // 使用 id 定位并点击 login_button 按钮
  await page.click("#login_button");

  // 填写结算信息
  await page.fill("#TextField1", info.lastname);
  await page.fill("#TextField0", info.firstname);
  await page.fill("#TextField3", info.address);
  await page.fill("#TextField4", info.home);
  //   await page.click("button.place-order");
  //   await page.check("#confirmed-address");
  try {
    const element = page.locator("#confirmed-address");

    if ((await element.count()) > 0) {
      for (let i = 0; i < count; i++) {
        // 点击每一个匹配的元素
        await elements.nth(i).click();
        console.log(`Clicked element ${i + 1}.`);
      }
    }
  } catch {
    (x) => {
      console.warn(x);
    };
  }
  await page.click('button#checkout-pay-button[type="submit"]');
  await page.fill("#ccNumber_disp", "1234567890123456");
  await page.fill("#ccExpirationMonth", "12");
  await page.fill("#ccExpirationYear_disp", "29");
  await page.fill("#securityCode", "123");
  await page.click("#exec-button");
  // 确认订单已提交
  //   await page.waitForSelector("div.order-confirmation");
  console.log("Order placed successfully!");

  // 关闭浏览器
  await browser.close();
})();
